<template>
<!-- 只有总页数大于1时才显示 -->
  <div class="pager-container" v-if="pageNumber > 1">
    <a @click="handleClick(1)" 
       :class="{ disabled: current === 1 }">
      |&lt;&lt;
    </a>
    <a @click="handleClick(current - 1)" :class="{ disabled: current === 1 }">
      |&lt;
    </a>
    <a v-for="(n,i) in numbers" 
       :key="i" 
       :class="{active:n == current}">
      {{n}}
    </a>
    <a @click="handleClick(current + 1)" 
       :class="{ disabled: current === pageNumber }">
      &gt;|
    </a>
    <a  @click="handleClick(pageNumber)" 
        :class="{ disabled: current === pageNumber }">
      &gt;&gt;|
    </a>
  </div>
</template>

<script>
export default {
  props:{
    current:{
      type:Number,
      default:1
    },
    total:{
      type:Number,
      default:1
    },
    limit:{//一页显示多少数据
      type:Number,
      default:10
    },
    visibleNumber:{//可显示的页数
      type:Number,
      default:10
    }
  },
  computed:{
    // 总页数
    pageNumber(){
      return Math.ceil(this.total / this.limit);
    },
    //可见的最小页数
    visibleMin(){
      let min = this.current - Math.floor( this.visibleNumber / 2 ); 
      if(min < 1){
        min = 1;
      }
      return min;
    },
    visibleMax(){
      let max = this.visibleMin + this.visibleNumber;
      if(max > this.pageNumber){
        max = this.pageNumber
      }
      return max;
    },
    numbers(){
      let arr=[];
      //提醒
      if(this.visibleMin > this.visibleMax){
        throw '当前页大于总页数'
      }
      for (let i = this.visibleMin; i < this.visibleMax; i++) {
        arr.push(i);
      }
      return arr;
    }
  },
  methods:{
    handleClick(newPage){
      if(newPage < 1){
        newPage = 1
      }
      if(newPage > this.pageNumber){
        newPage = this.pageNumber
      }
      if(newPage === this.current)
      {
        return;
      }
      //通知父组件更改数据
      this.$emit('pageChange',newPage);
    }
  }
};
</script>

<style lang="less" scoped>
@import "~@/styles/var.less";
.pager-container{
  display: flex;
  justify-content: center;
  margin: 20px 0;
  a{
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    &.disabled{
      color: @lightWords;
      cursor: not-allowed;
    }
    &.active {
      color: @words;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>